package com.blackcat.dynamicexcel.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 驼峰法-下划线互转
 * @author zhanghui
 * @since 2023/1/7 16:33
 */
public class UnderlineToCamelUtils {

    /**
     * 下划线转驼峰法
     * @author : zhanghui
     * @since : 2023/1/7 16:47
     * @param line 源字符串
     * @param smallCamel 首字母是否大小写
    */
    public static String underlineToCamel(String line,boolean smallCamel){
        if(line==null||"".equals(line)){
            return "";
        }
        StringBuffer sb=new StringBuffer();
        Pattern pattern=Pattern.compile("([A-Za-z\\d]+)(_)?");
        Matcher matcher=pattern.matcher(line);
        while(matcher.find()){
            String word=matcher.group();
            sb.append(smallCamel&&matcher.start()==0?Character.toLowerCase(word.charAt(0)):Character.toUpperCase(word.charAt(0)));
            int index=word.lastIndexOf('_');
            if(index>0){
                sb.append(word.substring(1, index).toLowerCase());
            }else{
                sb.append(word.substring(1).toLowerCase());
            }
        }
        return sb.toString();
    }

    /**
     * 驼峰法转下划线
     * @author : zhanghui
     * @since : 2023/1/7 16:49
     * @param line 源字符串
     * @param toUpperCase 字符是否大写
    */
    public static String camelToUnderline(String line,Boolean toUpperCase){
        if(line==null||"".equals(line)){
            return "";
        }
        line=String.valueOf(line.charAt(0)).toUpperCase().concat(line.substring(1));
        StringBuffer sb=new StringBuffer();
        Pattern pattern= Pattern.compile("[A-Z]([a-z\\d]+)?");
        Matcher matcher=pattern.matcher(line);
        while(matcher.find()){
            String word=matcher.group();
            if (toUpperCase){
                sb.append(word.toUpperCase());
            }else {
                sb.append(word.toLowerCase());
            }
            sb.append(matcher.end()==line.length()?"":"_");
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        String line="I_HAVE_AN_IPANG3_PIG";
        System.out.println("转驼峰首字母小写："+underlineToCamel(line,true));
        System.out.println("转驼峰首字母大写："+underlineToCamel(line,false));
        String str = "iHaveAnIpang3Pig";
        System.out.println("转下划线字母小写："+camelToUnderline(str,false));
        System.out.println("转下划线字母大写："+camelToUnderline(str,true));

//        转驼峰首字母小写：iHaveAnIpang3Pig
//        转驼峰首字母大写：IHaveAnIpang3Pig
//        转下划线字母小写：i_have_an_ipang3_pig
//        转下划线字母大写：I_HAVE_AN_IPANG3_PIG
    }

}
